<template>
  <el-dialog v-if="load" :close-on-click-modal="false" v-model="visible" align-center width="1200px" :z-index="2000"
    @close="handleClose">
    <template #title>
      <div>
        批量关联1688
        <small class="ml-3 text-red-600">注意：批量关联时会过滤无1688采购链接的数据</small>
      </div>
    </template>
    <div>
      <vxe-table :data="data" border>
        <vxe-colgroup title="公司sku信息">
          <vxe-column field="sku" title="sku" width="100"></vxe-column>
          <vxe-column field="sku_specification" title="属性" width="120">
            <template #default="{ row }">
              <VText :value="row.sku_specification" line="3" />
            </template>
          </vxe-column>
          <vxe-column title="图片" width="90">
            <template #default="{ row }">
              <VImage :src="row.main_img" size="70px" />
            </template>
          </vxe-column>
          <vxe-column field="sku_cn_title" title="产品名称" width="120">
            <template #default="{ row }">
              <VText :value="row.sku_cn_title" :line="4" />
            </template>
          </vxe-column>
          <vxe-column field="purchase_price" title="采购价格" width="100"></vxe-column>
        </vxe-colgroup>
        <vxe-colgroup title="1688关联信息">
          <template #header>
            <div class="flex justify-between">
              <div>1688关联信息</div>
              <el-button link type="primary" :loading="loadings.batchMatch" @click="batchMatch">更新1688属性</el-button>
            </div>
          </template>
          <vxe-column field="subject" title="1688产品名称" width="140">
            <template #default="{ row }">
              <VText :value="row.subject" :line="4" />
            </template>
          </vxe-column>
          <vxe-column title="起批量" width="70">
            <template #default="{ row }">
              {{ row.ali_min_order_quantity }}
            </template>
          </vxe-column>
          <vxe-column field="age" title="图片" width="90">
            <template #default="{ row }">
              <VImage :src="row.ali_main_image" size="70px" />
            </template>
          </vxe-column>
          <vxe-column field="age" title="属性" min-width="120">
            <template #default="{ row }">
              <VSelect v-model="row.seclected_sku_info" multiple collapse-tags filterable clearable
                :options="(row.ali_sku_info || []).map(d => ({ label: '' + d.attribute_name, value: d.sku_id }))"
                class="w-80" @change="({ value }) => selectChange(value, row)" />
              <div class="grid grid-cols-7 mt-2 border">
                <div class="border-b p-1 col-span-2">属性</div>
                <div class="border-b p-1 col-span-2">数量</div>
                <div class="border-b p-1 col-span-2">单价</div>
                <div class="border-b p-1"></div>
                <template v-for="(d, i) in row.assoc_sku_info" :key="i">
                  <div class="border-b p-1 flex items-center col-span-2">{{ d.attribute_name }}</div>
                  <div class="border-b p-1 flex items-center col-span-2">
                    <el-input-number v-model="d.sku_num" :controls="false" :min="0" :step="0.01" :precision="0"
                      placeholder="请输入" class="w-full" @change="skuNumChange(d, row)" />
                  </div>
                  <div class="border-b p-1 flex items-center col-span-2">{{ XEUtils.toFixed(d.sku_price, 2) }}</div>
                  <div class="border-b p-1 flex items-center">
                    <el-button link type="primary"
                      @click="row.seclected_sku_info.splice(i, 1) && selectChange(row.seclected_sku_info, row)">移除</el-button>
                  </div>
                </template>
              </div>
            </template>
          </vxe-column>
        </vxe-colgroup>
      </vxe-table>
    </div>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings.submit" @click="submit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import api from '../api'
import { ElMessage } from 'element-plus'
import XEUtils from 'xe-utils'
const load = ref(false)
const visible = ref(false)
const success = ref(false)
let loadings = reactive({})
const data = ref([])
const emit = defineEmits(['close', 'success'])

// 打开弹窗
const open = async (selection) => {
  // if (selection && !selection.length) {
  //   ElMessage.warning('请先选择行!')
  //   return
  // }
  if (!load.value) {
    load.value = true
    await 1
  }
  const res = await api.detail({ p_ids: selection.map(d => d.p_id) })
  data.value = res.data.filter(d => d.goods_link_type === 1)
  const filterNum = res.data.length - data.value.length
  if(filterNum) {
    ElMessage.warning(`已自动过滤${filterNum}条无1688采购链接的数据`)
  }
  success.value = false
  loadings = reactive({})
  visible.value = true
}

// 匹配
const batchMatch = () => {
  loadings.batchMatch = true
  api.batchMatch({ p_ids: data.value.map(d => d.p_id) }).then(res => {
    data.value = res.data.map((d) => Object.assign({}, data.value.find(da => da.p_id === d.p_id) || {}, d, { seclected_sku_info: [], assoc_sku_info: [] }))
    ElMessage.success('匹配成功')
  }).finally(() => {
    loadings.batchMatch = false
  })
}
const selectChange = (val, row) => {
  const { ali_price_ranges, assoc_sku_info, ali_sku_info } = row
  row.assoc_sku_info = row.assoc_sku_info.filter(d => val.includes(d.sku_id))
  val.forEach(v => {
    if (assoc_sku_info.some(d => d.sku_id === v)) return
    const item = {
      ...ali_sku_info.find(d => d.sku_id === v) || {},
      sku_num: row.ali_min_order_quantity,
    }
    if (ali_price_ranges.length > 1) {
      item.sku_price = ali_price_ranges[0]?.price
    }
    row.assoc_sku_info.push(item)
  })
}

const skuNumChange = (item, row) => {
  const { ali_price_ranges } = row
  if (ali_price_ranges.length < 2) {
    return
  }
  const allNum = row.assoc_sku_info.reduce((acc, cur) => acc += (+cur.sku_num || 0), 0)
  const { price } = ali_price_ranges.findLast(d => allNum >= d.startQuantity) || ali_price_ranges[0] || { price: 0 }
  row.assoc_sku_info.forEach(d => {
    d.sku_price = price
  })
}

// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
  success.value && emit('success')
}
// 提交
const submit = () => {
  loadings.submit = true
  api.batchAssoc({ products: data.value }).then(res => {
    success.value = true
    ElMessage.success('操作成功')
    close()
  }).finally(() => {
    loadings.submit = false
  })
}

defineExpose({ open })
</script>